import { login_api } from "@/api";
import { getToken, setToken, removeToken } from "@/utils/cookies";
import { Message } from "element-ui";
import { resetRouter } from "@/router";

const getDefaultState = () => {
  return {
    token: getToken(),
    account: "",
    name: "",
    avatar: "",
    roles: [],
  };
};

const state = getDefaultState();

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState());
  },
  SET_TOKEN: (state, token) => {
    state.token = token;
  },
  SET_ACCOUNT: (state, name) => {
    state.account = name;
  },
  SET_NAME: (state, name) => {
    state.name = name;
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar;
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles;
  },
};

const actions = {
  // 登录
  async login({ commit }, userInfo) {
    const { data: res } = await login_api.login(userInfo);
    const { code, message, token } = res;
    if (code !== 200) {
      return Message.error(message);
    }
    commit("SET_TOKEN", token);
    setToken(token);
  },

  // get user info
  async getUserInfo({ commit }) {
    const { data: res } = await login_api.getUserInfo();
    if (res.code == 200) {
      const { account, username, avatar, roles } = res.data;
      commit("SET_ACCOUNT", account);
      commit("SET_NAME", username);
      commit("SET_AVATAR", avatar);
      commit("SET_ROLES", roles);
    }
  },

  // user logout
  logout({ commit }) {
    removeToken(); // must remove  token  first
    resetRouter();
    commit("RESET_STATE");
  },

  // remove token
  resetToken({ commit }) {
    return new Promise((resolve) => {
      removeToken(); // must remove  token  first
      commit("RESET_STATE");
      resolve();
    });
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
